package com.edais.actions;

import com.edais.domain.*;
import com.edais.domain.gift.PointGrade;
import com.edais.log.IpLog;
import com.edais.service.*;
import com.edais.service.gift.PointAccountService;
import com.edais.util.*;
import com.edais.util.weixinAbout.SendWeiXinUtil;
import com.edais.vo.BankVo;
import com.edais.vo.UserBankCardVo;
import com.yunzhi.domain.RequestHeader;
import com.yunzhi.domain.ResultCode;
import com.yunzhi.domain.ResultConstant;
import com.yunzhi.domain.ResultDTO;
import com.yunzhi.util.RequestUtil;
import com.yunzhi.util.ResponseUtil;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;



@Controller
@RequestMapping("/investmentCenter")

public class CenterAction  implements Serializable{
	private static final Log logger = LogFactory.getLog(CenterAction.class);

	@Autowired
	private CenterService centerService;
	@Autowired
	private UserService userService;
	@Autowired
	private EPlanAssignService assignService;
	@Autowired
	private LoanService loanService;
	@Autowired
	private RateRisesCouponsService rateRisesCouponsService;
	@Autowired
	private SMSService sMSService;
	
	@Autowired
	private WeixinBindingService weixinBindingService;
	
	@Autowired
	private CaptchaService captchaService;
	
	@Autowired
	private SystemIdWorkerService systemIdWorkerService;
	
	@Autowired
	private UserCardService userCardService;
	
	@Autowired
	private UserVouchersService userVouchersService;
	
	@Autowired
	private JkxyService jkxyService;
	
	@Autowired
	private ShopVouchersService shopVouchersService;
	
	@Autowired
	private PointService pointService;
	
	@Autowired
	private PointAccountService pointAccountService;
	
	@Autowired
	private UserExtractInfoService userExtractInfoService;
	
	
	 
	/** 账户余额
	 * @param request
	 * @return response
	 * @throws Exception */
	@RequestMapping(value = "/getAccountBalance")
	public void getAccountBalance(HttpServletRequest request, HttpServletResponse response){
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		// 解密请求参数
		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
		String userId = paramsMap.get("userId");      // 用户id
		
		if(null==userId){
			userId = (String) request.getAttribute("userId");
		}

		if (StringUtils.isBlank(userId)) {         // 用户id为空
			logger.debug("/investmentCenter/getAccountBalance 传入参数为空：用户id");
			String result = CommonUtil.setResultStringCn(
				new HashMap<String, Object>(),Consts.ERROR_CODE,
				Consts.ErrorMsg.MSG00001,Message.CnDescriptionExpression.BUSINESSE_ERROR);
			// 处理返回结果
			CommonUtil.responseJson(result, response);
			return;
		}

		try {
			Map<String, Object> pageMode = new HashMap<String, Object>();
			pageMode.put("userId", userId);

			Map resMap = centerService.getCusBalance(pageMode);
			if (resMap != null && "00000".equals(resMap.get("rescode"))) {
				String acctBalance = resMap.get("ACCTBALANCE") + "";
				jsonMap.put("balanceMoney", acctBalance == null || "".equals(acctBalance) ? "0.00" : acctBalance);// 余额
			} else {
				logger.error("购买鼓钱包调用核心E300012失败:" + resMap.get("resmsg"));
				String result = CommonUtil.setResultStringCn(
					new HashMap<String, Object>(), Consts.ERROR_CODE,
					Consts.ErrorMsg.MSG00001,
					Message.CnDescriptionExpression.QUERY_FAILED);
				CommonUtil.responseJson(result, response);
				return;
			}
			
			String result = CommonUtil.setResultStringCn(
				jsonMap,Consts.SUCCESS_CODE, Consts.SUCCESS_DESCRIBE, "");
			// 处理返回结果
			CommonUtil.responseJson(result, response);

		} catch (Exception e) {
			logger.error("/investmentCenter/getAccountBalance 异常:" + e.getMessage());
			String result = CommonUtil.setResultStringCn(
				new HashMap<String, Object>(),Consts.ERROR_CODE,
				Consts.ErrorMsg.MSG00001,Message.CnDescriptionExpression.QUERY_FAILED);
			// 处理返回结果
			CommonUtil.responseJson(result, response);
			return;
		}
	}

	/** 获取支持的银行列表
	 * @param request
	 * @return response
	 * @throws Exception */
	@RequestMapping(value = "/getBanks")
	public void getBanks(HttpServletRequest request, HttpServletResponse response){
		Map<String,Object> jsonMap = new HashMap<String,Object>();
		// 解密请求参数
		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);

		try {
			Map<String,Object> bankParam = new HashMap<String,Object>();
			bankParam.put("eanble", "Y");
			bankParam.put("supportType", "('PHONE','WEBANDPHONE')");
			bankParam.put("platformEnName", "ZHIFUTONGPAY");
			List<BankVo> bankVoList = centerService.getBanks(bankParam);
			if(bankVoList != null){
				jsonMap.put("bankList", bankVoList);
			}else{
				String result = CommonUtil.setResultStringCn(
					new HashMap<String, Object>(),Consts.ERROR_CODE,
					Consts.ErrorMsg.MSG00001,Message.CnDescriptionExpression.BUSINESSE_ERROR);
				// 处理返回结果
				CommonUtil.responseJson(result, response);
				return;
			}
			
			String result = CommonUtil.setResultStringCn(
				jsonMap,Consts.SUCCESS_CODE, Consts.SUCCESS_DESCRIBE, "");
			// 处理返回结果
			CommonUtil.responseJson(result, response);
		} catch (Exception e) {
			logger.error("investmentCenter/getBanks 异常:" + e.getMessage());
			String result = CommonUtil.setResultStringCn(
				new HashMap<String, Object>(),Consts.ERROR_CODE,
				Consts.ErrorMsg.MSG00001,Message.CnDescriptionExpression.BUSINESSE_ERROR);
			// 处理返回结果
			CommonUtil.responseJson(result, response);
		}
	}

	/** 查询回款卡号
	 * @param request
	 * @return response
	 * @throws Exception */
	@RequestMapping(value = "/getRecePayBank")
	public void getRecePayBank(HttpServletRequest request, HttpServletResponse response){

		Map<String, Object> jsonMap = new HashMap<String, Object>();

		String logInfo = "查询回款卡号—getRecePayBank ";
		logger.info(logInfo+"开始");
		//签名校验
		if (!RequestUtil.validSign(request)) {
			logger.info(logInfo+"无效签名");
			ResponseUtil.write(response, ResultConstant.INVALID_SIGN);
			return;
		}

		//token校验
		if (!RequestUtil.validToken(request)) {
			logger.info(logInfo+"无效token");
			ResponseUtil.write(response, ResultConstant.INVALID_TOKEN);
			return;
		}

		//未登录校验
		RequestHeader header = RequestUtil.decodeHeader(request);
		if (header.getUserId() == null) {
			logger.info(logInfo+"未登录");
			ResponseUtil.write(response, ResultConstant.NOT_LOGIN);
			return;
		}
		// 用户id
		String userId =  header.getUserId().toString();
		logInfo=logInfo+userId;

		if (StringUtils.isBlank(userId)) { // 用户id为空
			logger.debug("investmentCenter/getRecePayBank 传入参数为空:用户id");
            ResultDTO resultDTO=new ResultDTO(ResultCode.FAILED,"用户id为空");
            resultDTO.setRecord(jsonMap);
            ResponseUtil.write(response,resultDTO);
			return;
		}
		try {
			HashMap<String, Object> userPayCdParam = new HashMap<String, Object>();
			userPayCdParam.put("isValid", "Y");
			userPayCdParam.put("userId", userId);
			userPayCdParam.put("isBinding", "Y");
			UserBankCardVo userRecePayCard = centerService.getRecePayBank(userPayCdParam);

			if (userRecePayCard == null) {
				jsonMap = BeanUtil.getMapFromBean(new UserBankCardVo());
			} else {
				jsonMap = BeanUtil.getMapFromBean(userRecePayCard);
			}

			// 查询当月剩余快速提现次数
			Map<String, Object> userQuickReqMap = new HashMap<String, Object>();
			userQuickReqMap.put("userId", userId);
			// 判断当月是否还有快速提现次数
			Integer quickWithdrawCount = 0;
			// 添加快速提现相关提示信息
			String systemQuickAmount = rateRisesCouponsService.findParamValueByName("quick_withdraw_amount");
			// 查询提现开关
			String quickWithdrawFlag = rateRisesCouponsService.findParamValueByName("quick_withdraw_flag");

			// 查询用户等级信息
//			PointGrade userPg = userExtractInfoService.queryPointGradeByUserId(userId);
			//TODO 解决调试不通
			PointGrade userPg = new PointGrade();
			userPg.setGrade("1");

			// 查询等级提现相关信息
			ExtractConfig userEc = userExtractInfoService.queryExtractConfigByPointGrade(userPg.getGrade());
			Map<String, Object> userExParams = new HashMap<String, Object>();
			userExParams.put("userId", userId);
			UserExtractInfo userExctractInfo = userExtractInfoService.getUserExtractInfo(userExParams);
			SimpleDateFormat extractDaySdf = new SimpleDateFormat("yyyy-MM-dd");
			SimpleDateFormat extractMonthSdf = new SimpleDateFormat("yyyy-MM");
			if (userExctractInfo == null) {
				userExctractInfo = new UserExtractInfo();
				userExctractInfo.setUserId(Integer.parseInt(userId));
				userExctractInfo.setUserMobile(userRecePayCard == null ? "" : userRecePayCard.getPhone_no());
				userExctractInfo.setUserName(userId);
				userExctractInfo.setExtractDay(extractDaySdf.format(new Date()));
				userExctractInfo.setExtractMonth(extractMonthSdf.format(new Date()));
				userExctractInfo.setExtractNormalMonthNumber(0);
				userExctractInfo.setExtractNormalMonthAmount(BigDecimal.ZERO);
				userExctractInfo.setExtractQuickDayNumber(0);
				userExctractInfo.setExtractQuickDayAmount(BigDecimal.ZERO);
			}

			Integer normalMonthRemainNumber = userEc.getNormalMonthNumber();
			if (extractMonthSdf.format(new Date()).equals(userExctractInfo.getExtractMonth())) {
				normalMonthRemainNumber = userEc.getNormalMonthNumber()
						- userExctractInfo.getExtractNormalMonthNumber();
			}
			if (normalMonthRemainNumber < 0) {
				normalMonthRemainNumber = 0;
			}
			BigDecimal quickDayRemainAmount = userEc.getQuickDayAmount();
			quickWithdrawCount = userEc.getQuickDayNumber();
			if (extractDaySdf.format(new Date()).equals(userExctractInfo.getExtractDay())) {
				quickDayRemainAmount = userEc.getQuickDayAmount().subtract(userExctractInfo.getExtractQuickDayAmount());
				quickWithdrawCount = userEc.getQuickDayNumber() - userExctractInfo.getExtractQuickDayNumber();
			}
			if (quickDayRemainAmount.compareTo(BigDecimal.ZERO) < 0) {
				quickDayRemainAmount = BigDecimal.ZERO;
			}
			if (quickWithdrawCount < 0) {
				quickWithdrawCount = 0;
			}
			// 查询温馨提示相关信息拼接
			NumberFormat nf = new DecimalFormat(",###");
			String extractTip = userService.getSysSettingHtmlInfo("t_extract_tip");
			String quickWithdrawTip = userService.getSysSettingHtmlInfo("t_extract_quick_tip");
			String normalExtractTip = userService.getSysSettingHtmlInfo("t_extract_normal_tip");
			// 旧版本
			String quickAmountDesc = "";

			Map<String, String> phMap = new HashMap<String, String>();
			phMap.put("quickDayRemainAmount", nf.format(quickDayRemainAmount));
			phMap.put("quickSingleAmount", nf.format(userEc.getQuickSingleAmount()));
			phMap.put("quickDayNumber", userEc.getQuickDayNumber().toString());
			phMap.put("quickDayAmount", nf.format(userEc.getQuickDayAmount()));
			phMap.put("normalMonthNumber", userEc.getNormalMonthNumber().toString());
			phMap.put("normalMonthRemainNumber", normalMonthRemainNumber.toString());

			quickWithdrawTip = PlaceholderUtils.resolvePlaceholders(quickWithdrawTip, phMap);
			quickAmountDesc = PlaceholderUtils.resolvePlaceholders(extractTip, phMap);
			normalExtractTip = PlaceholderUtils.resolvePlaceholders(normalExtractTip, phMap);
			// 兼容老版本
			jsonMap.put("quickWithdrawCount", quickWithdrawCount); // 快速提现次数
			jsonMap.put("systemQuickAmount", quickDayRemainAmount); // 快速提现剩余金额
			jsonMap.put("quickWithdrawFlag", quickWithdrawFlag); // 快速提现开关
			jsonMap.put("quickWithdrawTip", quickWithdrawTip); // 快速提现提示
			jsonMap.put("normalWithdrawTip", normalExtractTip); // 普通提现提示
			jsonMap.put("quickAmountDesc", quickAmountDesc); // 提现文案
			jsonMap.put("quickCountDesc", "");

			logger.info(logInfo+"结束");
			//下一提现日提醒
			ResultDTO resultDTO=new ResultDTO(ResultCode.SUCCESS,Consts.SUCCESS_DESCRIBE);
			resultDTO.setRecord(jsonMap);
			ResponseUtil.write(response,resultDTO);
		} catch (Exception e) {
			logger.error(logInfo+" 异常:" ,e);
			ResultDTO resultDTO=new ResultDTO(ResultCode.FAILED,Message.CnDescriptionExpression.BUSINESSE_ERROR);
			ResponseUtil.write(response,resultDTO);
		}
	}

	/** E400012获取鼓钱包标的列表
	 * @param request
	 * @return response
	 * @throws Exception */
	@RequestMapping(value = "/getReadyLoanList")
	public void getReadyLoanList(HttpServletRequest request, HttpServletResponse response){
		Integer current = 1;
		Integer pageSize = 12;
		String loanStatus = "READY";  // 标的状态（READY：招标中）
		
		//获取鼓钱包所有产品类型
		//String loantype = String.valueOf(Consts.GQB);      // 103：鼓钱包
		String loantype = "";
		try {
			//"('CREDIT_EXPIRE','CREDIT_MATCH_SUCCESS')"
			loantype ="( "+ this.assignService.getAllProductType()+" )";
		} catch (Exception e1) {
			e1.printStackTrace();
		}

		// 解密请求参数
		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
		String currentStr = paramsMap.get(Consts.Page.PAGE_CURRENT_NAME);   // 当前页
		String pageSizeStr = paramsMap.get(Consts.Page.PAGE_SIZE_NAME);     // 页大小

		if (currentStr != null && !("".equals(currentStr))) {
			current = Integer.parseInt(currentStr);
		}
		if (pageSizeStr != null && !("".equals(pageSizeStr))) {
			pageSize = Integer.parseInt(pageSizeStr);
		}

		try {
			// 获取标的列表
			Map<String, Object> jsonMap = this.centerService.getReadyLoan(loanStatus, loantype, current, pageSize);

			String result = CommonUtil.setResultStringCn(jsonMap, Consts.SUCCESS_CODE, Consts.SUCCESS_DESCRIBE,"");
			// 处理返回结果
			CommonUtil.responseJson(result, response);

		} catch (Exception e) {
			logger.error("investmentCenter/getReadyLoanList 异常: " + e.getMessage());
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(),
				Consts.ERROR_CODE, Consts.ErrorMsg.MSG00001,
				Message.CnDescriptionExpression.BUSINESSE_ERROR);
			// 处理返回结果
			CommonUtil.responseJson(result, response);

			return;
		}
	}

	

	/**
	 * 购买时是否可填邀请码
	 */
	@RequestMapping(value = "/getInvitationCdStus")
	public void getInvitationCdStus(HttpServletRequest request, HttpServletResponse response){
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		// 解密请求参数
		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
		String userId = paramsMap.get("userId");// 用户id
		
		if (StringUtils.isBlank(userId)) {
			logger.debug("investmentCenter/getInvitationCdStus 传入用户id为空");
			String result = CommonUtil.setResultStringCn(
				new HashMap<String, Object>(),Consts.ERROR_CODE, Consts.ErrorMsg.MSG00001,Message.CnDescriptionExpression.BUSINESSE_ERROR);
			// 处理返回结果
			CommonUtil.responseJson(result, response);
			return;
		}
		
		try{
			jsonMap = centerService.getInvitationCdStus(userId);
			String result = CommonUtil.setResultStringCn(
				jsonMap,Consts.SUCCESS_CODE, Consts.SUCCESS_DESCRIBE, "");
			// 处理返回结果
			CommonUtil.responseJson(result, response);
			
		}catch(Exception ex){
			logger.debug("investmentCenter/getInvitationCdStus 异常" + ex.getMessage());
			String result = CommonUtil.setResultStringCn(
				new HashMap<String, Object>(),Consts.ERROR_CODE, Consts.ErrorMsg.MSG00001,Message.CnDescriptionExpression.BUSINESSE_ERROR);
			// 处理返回结果
			CommonUtil.responseJson(result, response);
		}
	}
	
	/** 余额购买，且余额>=理财计划购买金额
	 * @param request
	 * @return response
	 * @throws Exception */
	@RequestMapping(value = "/buyProductByBalance")
	public void buyProductByBalance(HttpServletRequest request, HttpServletResponse response){
		Map<String, Object> jsonMap = new HashMap<String, Object>();

		// 解密请求参数
		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
		// 用户id
		String userID = paramsMap.get("userId");
		// 购买理财计划金额
		String buyAmount = paramsMap.get("buyAmount");
		// 购买理财计划id
		String financeID = paramsMap.get("financeID");
		// 资金流转方式
		String cycleMatchType = paramsMap.get("cycleMatchType");
		// 邀请码
		String invitationCd = paramsMap.get("invitationCd");
		
		String ip = CommonUtil.getClientIP(request);
		
		IpLogBean logBean = new IpLogBean();
		logBean.setIp(ip);
		logBean.setAction("余额购买");
		logBean.setUser(userID);
		logBean.setStatus(Consts.ERROR_CN);
		logBean.setDetail(userID+"在APP端进行了余额购买操作");
		
		Map resMap = new HashMap<String,Object>();
		
		if (StringUtils.isBlank(userID)
			|| StringUtils.isBlank(financeID)
			|| StringUtils.isBlank(cycleMatchType)) {
			logger.debug("investmentCenter/buyProductByBalance 传入参数为空");
			if(StringUtils.isNotBlank(ip)){
				IpLog.printIpLog(logBean);
			}
			
			// 处理返回结果
			String result = CommonUtil.setResultStringCn(
				new HashMap<String, Object>(),Consts.ERROR_CODE, 
				Consts.ErrorMsg.MSG00001,Message.CnDescriptionExpression.BUSINESSE_ERROR);	
			CommonUtil.responseJson(result, response);
			return;
		}
		
		if(StringUtils.isBlank(buyAmount)){
			logger.debug("investmentCenter/buyProductByBalance 未输入购买金额");
			if(StringUtils.isNotBlank(ip)){
				IpLog.printIpLog(logBean);
			}
			String result = CommonUtil.setResultStringCn(
				new HashMap<String, Object>(), Consts.CHECK_CODE, "", Message.CnDescriptionExpression.AMOUNT_IS_NULL);
			// 处理返回结果
			CommonUtil.responseJson(result, response);
			return;
		}
		
		try {
			/** 获取购买的产品是否在预售期内 */
			String checkResult = centerService.checkPlanSellTime(financeID);
			if (!"true".equals(checkResult)) {
				logger.debug("investmentCenter/buyProductByBalance 购买活动未开始或者已结束");
				if(StringUtils.isNotBlank(ip)){
					IpLog.printIpLog(logBean);
				}
				String msgCn;
				if("buy.has.not.started".equals(checkResult)){
					msgCn = Message.CnDescriptionExpression.BUY_HAS_NOT_STARTED;
				}else if("buy.has.ended".equals(checkResult)){
					msgCn = Message.CnDescriptionExpression.BUY_HAS_ENDED;
				}else{
					msgCn = Message.CnDescriptionExpression.PLAN_HAS_NOT_OPENED;
				}
				String result = CommonUtil.setResultStringCn(
					new HashMap<String, Object>(), Consts.CHECK_CODE, "", msgCn);
				CommonUtil.responseJson(result, response);
				return;
			}
			

			/** 获取用户是否实名认证,对于实名认证用户取得身份证号和姓名 */
			User user = userService.getUserDetail(userID);
			// 判断用户是否实名认证
			if (!"Y".equals(user.getSina_idcard_validate())
					|| !"1".equals(user.getIs_create_acct())
					|| !"Y".equals(user.getIdcard_validate())) {
				logger.debug("investmentCenter/buyProductByBalance 用户没有经过实名认证");
				if(StringUtils.isNotBlank(ip)){
					IpLog.printIpLog(logBean);
				}
				// 没有经过实名认证不能进行购买
				String result = CommonUtil.setResultStringCn(
					new HashMap<String, Object>(), Consts.CHECK_CODE, "", Message.CnDescriptionExpression.AUTHENTICATION_IS_NOT);
				CommonUtil.responseJson(result, response);
				return;
			}
			
			// 购买金额检查（必须是1000元以上,且小数点后2位）
			boolean flag = buyAmount.matches("^[0-9]*[\\.]{0,1}[0-9]{0,2}$");
			if (!flag) {
				logger.debug("购买鼓钱包时输入的购买金额非法，购买金额:" + buyAmount);
				if(StringUtils.isNotBlank(ip)){
					IpLog.printIpLog(logBean);
				}
				// 输入的值为非法字符
				String result = CommonUtil.setResultStringCn(
					new HashMap<String, Object>(), Consts.CHECK_CODE, "", Message.CnDescriptionExpression.BUYAMOUNT_IS_NON_STANDARD);
				CommonUtil.responseJson(result, response);
				return;
			}
			
			BigDecimal decBuyAmount = new BigDecimal(buyAmount);// 购买金额
			//投资金额的上下限检查
			Finance finance = centerService.getFinanceplanDetail(financeID,"");
			BigDecimal minInvestMoney = finance.getMin_buyer_amount();//最小投资金额
			BigDecimal maxBuyerAmount = finance.getMax_buyer_amount();//投资最大金额
			
			if((null != minInvestMoney && CommonUtil.checkAmount(decBuyAmount, minInvestMoney) < 0) || 
				(decBuyAmount.compareTo(BigDecimal.valueOf(0.00))==0)){
				//最小投资金额
				logger.debug("购买鼓钱包时购买金额低于最小投资金额，购买金额:" + decBuyAmount);
				if(StringUtils.isNotBlank(ip)){
					IpLog.printIpLog(logBean);
				}
				String result = CommonUtil.setResultStringCn(
					new HashMap<String, Object>(), Consts.CHECK_CODE, "", Message.CnDescriptionExpression.BUYAMOUNT_BELOW_MINAMOUNT);
				CommonUtil.responseJson(result, response);
				return;
			}
			
			if(null != maxBuyerAmount && CommonUtil.checkAmount(decBuyAmount, maxBuyerAmount) > 0){
				//购买最大金额
				logger.debug("购买鼓钱包时购买金额高于购买最大金额，购买金额:" + decBuyAmount);
				if(StringUtils.isNotBlank(ip)){
					IpLog.printIpLog(logBean);
				}
				String result = CommonUtil.setResultStringCn(
					new HashMap<String, Object>(), Consts.CHECK_CODE, "", Message.CnDescriptionExpression.BUYAMOUNT_EXCEEDS_MAXAMOUNT);
				CommonUtil.responseJson(result, response);
				return;
			}
			
			// 获取该用户的余额
			Map<String, Object> pageMode = new HashMap<String, Object>();
			pageMode.put("userId", userID);

			String acctBalance = "0.00";// 余额
			resMap = centerService.getCusBalance(pageMode);
			if (resMap != null && "00000".equals(resMap.get("rescode"))) {
				acctBalance = resMap.get("ACCTBALANCE") + "";
			} else {
				logger.error("购买鼓钱包调用核心E300012失败:" + resMap.get("resmsg"));
				if(StringUtils.isNotBlank(ip)){
					IpLog.printIpLog(logBean);
				}
				String result = CommonUtil.setResultStringCn(
					new HashMap<String, Object>(), Consts.ERROR_CODE, "", Message.CnDescriptionExpression.BUSINESSE_ERROR);
				CommonUtil.responseJson(result, response);
				return;
			}

			// 余额检查
			if ("0.00".equals(acctBalance) || StringUtils.isBlank(acctBalance)) {
				logger.debug("购买鼓钱包时余额不足,余额为:" + acctBalance);
				if(StringUtils.isNotBlank(ip)){
					IpLog.printIpLog(logBean);
				}
				String result = CommonUtil.setResultStringCn(
					new HashMap<String, Object>(), Consts.CHECK_CODE, "", Message.CnDescriptionExpression.BALANCE_IS_NOT_SUFFICIENT);
				CommonUtil.responseJson(result, response);
				return;
			}

			BigDecimal decBalance = new BigDecimal(acctBalance);// 余额

			// 余额-理财计划金额 < 0
			if (decBalance.compareTo(decBuyAmount) < 0) {
				logger.debug("购买鼓钱包时余额不足,余额差:" + (decBalance.subtract(decBuyAmount)));
				if(StringUtils.isNotBlank(ip)){
					IpLog.printIpLog(logBean);
				}
				String result = CommonUtil.setResultStringCn(
					new HashMap<String, Object>(), Consts.CHECK_CODE, "", Message.CnDescriptionExpression.BALANCE_IS_NOT_SUFFICIENT);
				CommonUtil.responseJson(result, response);
				return;
			}
			
			//增加邀请码校验
			if("Y".equals(finance.getIf_support_invicode())){
				String s = this.centerService.checkInviteCode(invitationCd==null?"":invitationCd, userID);
				if("N".equals(s)){
					logger.error("用户输入的邀请码不合法! 邀请码:" + invitationCd);
					if(StringUtils.isNotBlank(ip)){
						IpLog.printIpLog(logBean);
					}
					String result = CommonUtil.setResultStringCn(
						new HashMap<String, Object>(), Consts.ERROR_CODE, "", Message.CnDescriptionExpression.BUSINESSE_ERROR);
					CommonUtil.responseJson(result, response);
					return;
				}
			}
			
			//邀请码
			if("Y".equals(finance.getIf_support_invicode()) 
				&& !StringUtils.isBlank(invitationCd)
				&& !invitationCd.equalsIgnoreCase(user.getInvitation_code())){
				/**
				 * 1:输入邀请码的情况下，先判断此邀请码是否存在且非本人
				 * 2:如果有效且非本人，则判断被邀请人是否是首次加入“e计划”，
				 */
				int count = this.userService.getUserNotMeByInviteCode(invitationCd.toUpperCase(),userID);
				if(count > 0){
					pageMode.put("invitationCode", invitationCd.toUpperCase());
				}else{
					//邀请码不存在
					logger.error("用户输入的邀请码不存在! 邀请码:" + invitationCd);
					if(StringUtils.isNotBlank(ip)){
						IpLog.printIpLog(logBean);
					}
					String result = CommonUtil.setResultStringCn(
						new HashMap<String, Object>(), Consts.CHECK_CODE, "", Message.CnDescriptionExpression.INVITATIONCD_NOT_EXIST);
					CommonUtil.responseJson(result, response);
					return;
				}
			}else if("Y".equals(finance.getIf_support_invicode()) 
				&& !StringUtils.isBlank(invitationCd)
				&& invitationCd.equalsIgnoreCase(user.getInvitation_code())){
				//本人邀请码
				logger.error("用户输入了自己的邀请码! 邀请码:" + invitationCd);
				if(StringUtils.isNotBlank(ip)){
					IpLog.printIpLog(logBean);
				}
				String result = CommonUtil.setResultStringCn(
					new HashMap<String, Object>(), Consts.CHECK_CODE, "", Message.CnDescriptionExpression.PRIVATE_INVITATIONCD);
				CommonUtil.responseJson(result, response);
				return;
			}

			pageMode.put("planId", financeID);
			pageMode.put("sum", decBuyAmount);
			pageMode.put("buyAmount", buyAmount);
			pageMode.put("cycleMatchType", cycleMatchType);
			
			Map retMap = centerService.dealBuyProductByBalance(pageMode);
			if(retMap == null){
				if(StringUtils.isNotBlank(ip)){
					IpLog.printIpLog(logBean);
				}
				String result = CommonUtil.setResultStringCn(
					new HashMap<String, Object>(),Consts.ERROR_CODE, Consts.ErrorMsg.MSG00001,Message.CnDescriptionExpression.BUSINESSE_ERROR);
				// 处理返回结果
				CommonUtil.responseJson(result, response);
				return;
			}else{
				jsonMap.put("orderId", retMap.get("orderId"));
			}
			
			logBean.setStatus(Consts.SUCCESS_CN);
			if(StringUtils.isNotBlank(ip)){
				IpLog.printIpLog(logBean);
			}
			
			String result = CommonUtil.setResultStringCn(
				jsonMap,Consts.SUCCESS_CODE, Consts.SUCCESS_DESCRIBE, "");
			// 处理返回结果
			CommonUtil.responseJson(result, response);
			
		} catch (Exception e) {
			logger.error("investmentCenter/buyProductByBalance 异常:" + e.getMessage());
			if(StringUtils.isNotBlank(ip)){
				IpLog.printIpLog(logBean);
			}
			String result = CommonUtil.setResultStringCn(
				new HashMap<String, Object>(),Consts.ERROR_CODE, Consts.ErrorMsg.MSG00001,Message.CnDescriptionExpression.BUSINESSE_ERROR);
			// 处理返回结果
			CommonUtil.responseJson(result, response);
		}
	}
	
	/** 余额购买散标
	 * @param request
	 * @return response
	 * @throws Exception */
	@RequestMapping(value = "/buyLoanByBalance")
	public void buyLoanByBalance(HttpServletRequest request, HttpServletResponse response){
		Map<String, Object> jsonMap = new HashMap<String, Object>();

		// 解密请求参数
		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
		String userId = paramsMap.get("userId");// 用户id
		String buyCount = paramsMap.get("buyCount");// 购买份数
		String bidId = paramsMap.get("scatteredLoanId");// 购买散标id
		String setupFlag = paramsMap.get("setupFlag");// 发送标识（是来自网站用户，还是手机用户）:1：为来自网站的；2：来自手机的
		String cycleMatchType = paramsMap.get("cycleMatchType");// 循环匹配类型1、本息循环2、本金循环3、不循环
		String planId = paramsMap.get("planId");// 计划id
		String loanId = paramsMap.get("loanId");//标的ID
		String rateIds = paramsMap.get("rateIds");//加息券ID
		String investPeriod = paramsMap.get("investPeriod");
		String from = paramsMap.get("from");
		String remanDays=paramsMap.get("remanDays");//需要判断定期是天数还是月数
		String voucherId = paramsMap.get("voucherId");//使用的代金券Id
		
		
		String ip = CommonUtil.getClientIP(request);
		
		IpLogBean logBean = new IpLogBean();
		logBean.setIp(ip);
		logBean.setAction("余额购买");
		logBean.setUser(userId);
		logBean.setStatus(Consts.ERROR_CN);
		if("2".equals(setupFlag)){
			logBean.setDetail(userId+"在APP端进行了余额购买散标操作");
		}else{
			logBean.setDetail(userId+"在WEB端进行了余额购买散标操作");
		}
		
		try{
			Map<String,String> checkMap = buyLoanByBalanceCheck(paramsMap);
			if (null == checkMap
					|| !Consts.SUCCESS_CODE.equals(checkMap.get("code"))) {
				if(StringUtils.isNotBlank(ip)){
					IpLog.printIpLog(logBean);
				}
				String result = CommonUtil.setResultStringCn(
						new HashMap<String, Object>(), checkMap.get("code"),
						"", checkMap.get("message"));
				// 处理返回结果
				CommonUtil.responseJson(result, response);
				return;
			}
			
			// 购买主业务
			Map<String,Object> pageMode = new HashMap<String,Object>();
			if(StringUtils.isBlank(cycleMatchType)){
				cycleMatchType = "3";
			}
			
			pageMode.put("bidId", bidId);
			//pageMode.put("buyAmount", 	checkMap.get("buyAmount"));
			pageMode.put("buyAmount", 	buyCount);
			pageMode.put("cycleMatchType", cycleMatchType);
			pageMode.put("buyMedia", from);
			pageMode.put("userId", userId);
			pageMode.put("planId", planId);
			pageMode.put("loanId", loanId);
			pageMode.put("voucherId", voucherId);
			
			
			if(null==voucherId || "".equalsIgnoreCase(voucherId)){
				voucherId ="";
			}else{
				Map<String,Object> reqMap = new HashMap<String,Object>();
				reqMap.put("voucherId", voucherId);
				Map<String, Object> voucherMap = new HashMap<String, Object>();
				voucherMap = this.userVouchersService.queryUserVochersById(reqMap);
				if(Consts.ERROR_CODE.equalsIgnoreCase(String.valueOf(voucherMap.get("rescode")))){
					jsonMap.put("rescode", Consts.CHECK_CODE);
					String resMsg = "该代金券不存在！";
					jsonMap.put("resmsg_cn",resMsg);
					String result = CommonUtil.setResultStringCn(
							jsonMap,Consts.CHECK_CODE, resMsg, resMsg);
						// 处理返回结果
						CommonUtil.responseJson(result, response);
					return;
				}else{
					if(Consts.SUCCESS_CODE.equalsIgnoreCase(String.valueOf(voucherMap.get("rescode")))){
						UserVouchers  userVouchers = (UserVouchers)voucherMap.get("userVouchers");
						//根据代金券Id库存代金券信息
						Map<String, Object> voucherMap2 = new HashMap<String, Object>();
						voucherMap2 = this.userVouchersService.queryVochersInfoById(String.valueOf(userVouchers.getVoucher_type_id()));
						if(Consts.ERROR_CODE.equalsIgnoreCase(String.valueOf(voucherMap2.get("rescode")))){
							jsonMap.put("rescode", Consts.CHECK_CODE);
							String resMsg = "库存不足代金券异常";
							jsonMap.put("resmsg_cn",resMsg);
							String result = CommonUtil.setResultStringCn(
									jsonMap,Consts.CHECK_CODE, resMsg, resMsg);
								// 处理返回结果
								CommonUtil.responseJson(result, response);
							return;
						}
						if(new BigDecimal(buyCount).compareTo(userVouchers.getInvestment_amount())<0){
							jsonMap.put("rescode", Consts.CHECK_CODE);
							String resMsg = "您输入的金额未满足使用代金券规则";
							jsonMap.put("resmsg_cn",resMsg);
							String result = CommonUtil.setResultStringCn(
									jsonMap,Consts.CHECK_CODE, resMsg, resMsg);
								// 处理返回结果
								CommonUtil.responseJson(result, response);
			 			}
						VouchersRule vouchersRule = (VouchersRule)voucherMap2.get("vouchersRule");
						//需要界面告知是月数还是天数
						if(remanDays==null||"".equals(remanDays.trim())||"0".equals(remanDays.trim())){
							if(vouchersRule.getMinlockperiod()>Integer.parseInt(investPeriod)*30){
								jsonMap.put("rescode", Consts.CHECK_CODE);
								String resMsg = "所选代金券使用天数不能大于该定期封闭期天数，请重新选择！";
								jsonMap.put("resmsg_cn",resMsg);
								String result = CommonUtil.setResultStringCn(
										jsonMap,Consts.CHECK_CODE, resMsg, resMsg);
									// 处理返回结果
									CommonUtil.responseJson(result, response);
								return;
							}
						}else{
							if(vouchersRule.getMinlockperiod()>Integer.parseInt(remanDays)){
								jsonMap.put("rescode", Consts.CHECK_CODE);
								String resMsg = "所选代金券使用天数不能大于该定期封闭期天数，请重新选择！";
								jsonMap.put("resmsg_cn",resMsg);
								String result = CommonUtil.setResultStringCn(
										jsonMap,Consts.CHECK_CODE, resMsg, resMsg);
								// 处理返回结果
								CommonUtil.responseJson(result, response);
								return;
							}
						}
						pageMode.put("voucherMoney", vouchersRule.getVoucher_amount());
						
						if(userVouchers.getInvestment_amount().compareTo(vouchersRule.getInvestment_amount())!=0){
							jsonMap.put("rescode", Consts.CHECK_CODE);
							String resMsg = "代金券使用出现异常，请联系客服";
							jsonMap.put("resmsg_cn",resMsg);    
							String result = CommonUtil.setResultStringCn(
									jsonMap,Consts.CHECK_CODE, resMsg, resMsg);
								// 处理返回结果
							CommonUtil.responseJson(result, response);
							return;
			 			}
						
						if(userVouchers.getVoucher_amount().compareTo(vouchersRule.getVoucher_amount())!=0){
							jsonMap.put("rescode", Consts.CHECK_CODE);
							String resMsg = "代金券使用出现异常，请联系客服";
							jsonMap.put("resmsg_cn",resMsg);    
							String result = CommonUtil.setResultStringCn(
									jsonMap,Consts.CHECK_CODE, resMsg, resMsg);
								// 处理返回结果
							CommonUtil.responseJson(result, response);
							return;
			 			}
						
					}
				}
			}
			  
			String [] rateIdsArray = null;
			//购买散标前进行加息券的check
			if(StringUtils.isNotBlank(rateIds)){
				rateIdsArray = rateIds.split(",");
				
				if(rateIdsArray.length>0){
					List<RateRisesCoupons> couponsList = this.rateRisesCouponsService.getRateRisesListByRateIds(rateIdsArray);
					
					boolean checkProductType = true; 
					for(RateRisesCoupons coupons : couponsList){
						if(!coupons.getProduct_id().equals(planId)){
							checkProductType = false;
							break;
						}
					}
					String resMsg = "";
					if(!checkProductType){
						jsonMap.put("rescode", Consts.CHECK_CODE);
						resMsg = "对不起，您选择的加息券不是全部为定期加息券，请重新选择。";
						jsonMap.put("resmsg_cn",resMsg);
						String result = CommonUtil.setResultStringCn(
								jsonMap,Consts.CHECK_CODE, resMsg, resMsg);
							// 处理返回结果
							CommonUtil.responseJson(result, response);
						return;
					}else{
						if(rateIdsArray.length>1){
							jsonMap.put("rescode", Consts.CHECK_CODE);
							resMsg = "定期订单只能使用一张加息券，请重新选择！";
							jsonMap.put("resmsg_cn",resMsg);
							String result = CommonUtil.setResultStringCn(
									jsonMap,Consts.CHECK_CODE, resMsg, resMsg);
								// 处理返回结果
								CommonUtil.responseJson(result, response);
							return;
						}else{
							RateRisesCoupons useCoupons = couponsList.get(0);
							//需要界面告知是月数还是天数
							if(remanDays==null||"".equals(remanDays.trim())||"0".equals(remanDays.trim())){
								if(useCoupons.getRate_rises_days()!=Integer.parseInt(investPeriod)){
									jsonMap.put("rescode", Consts.CHECK_CODE);
									resMsg = "加息的期数和订单的借款期数不相同，请重新选择！";
									jsonMap.put("resmsg_cn",resMsg);
									String result = CommonUtil.setResultStringCn(
											jsonMap,Consts.CHECK_CODE, resMsg, resMsg);
										// 处理返回结果
										CommonUtil.responseJson(result, response);
									return;
								}
							}else{
								if(useCoupons.getRemanDays()!=Integer.parseInt(remanDays)){
									jsonMap.put("rescode", Consts.CHECK_CODE);
									resMsg = "加息的期数和订单的借款期数不相同，请重新选择！";
									jsonMap.put("resmsg_cn",resMsg);
									String result = CommonUtil.setResultStringCn(
											jsonMap,Consts.CHECK_CODE, resMsg, resMsg);
									// 处理返回结果
									CommonUtil.responseJson(result, response);
									return;
								}
							}
							
						}
					}
				}
			}
			//ouyy 增加协议需求修改的内容
			try {
				String agreementautoid=systemIdWorkerService.getCurrentNo();
				logger.info("定期购买 :agreementautoid="+agreementautoid);
				pageMode.put("agreementAutoid", agreementautoid);//协议编号
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				logger.error("定期购买加入自动生成的协议编号发生异常:"+e1);
				e1.printStackTrace();
				pageMode.put("agreementAutoid", "");//
			}
			try {
				if(StringUtils.isBlank(loanId)){
					bidId="0";
				}
				logger.info("定期购买 :loanId="+loanId);
				Map<String,Object> agrMap = centerService.getAgrnoAndAssno(Integer.parseInt(loanId));
				String agreementno =(String)agrMap.get("AGREEMENTNO");
				String assetno =(String)agrMap.get("ASSETNO");
				logger.info("定期购买 :agreementno="+agreementno);
				logger.info("定期购买 :assetno="+assetno);
				pageMode.put("agreementNo", agreementno);// 
				pageMode.put("assetNo", assetno);//
			} catch (Exception e2) {
				// TODO Auto-generated catch block
				logger.error("定期购买加入合同模板编号与资产包编号发生异常:"+e2);
				e2.printStackTrace();
				pageMode.put("agreementNo", "");// 
				pageMode.put("assetNo", "");//
			}
					
			
			
			Map retMap = centerService.dealBuyBidByBalance(pageMode);
			if(retMap == null){
				if(StringUtils.isNotBlank(ip)){
					IpLog.printIpLog(logBean);
				}
				String result = CommonUtil.setResultStringCn(
					new HashMap<String, Object>(),Consts.ERROR_CODE, "",Message.CnDescriptionExpression.BUSINESSE_ERROR);
				// 处理返回结果
				CommonUtil.responseJson(result, response);
				return;
			}
			logBean.setStatus(Consts.SUCCESS_CN);
			if(StringUtils.isNotBlank(ip)){
				IpLog.printIpLog(logBean);
			}
			//送一元购券
			try {
				String minMoney = userService.getSystemSettingValue("dqyyg_min_money");//起送金额
				if(StringUtil.isEmpty(minMoney)){
					minMoney = "5000";
				}
				int sentCount = Integer.valueOf(buyCount)/Integer.valueOf(minMoney);
				logger.info("用户"+userId+"定期购买"+buyCount+"元赠送电商一元购券:"+sentCount+"张");
				if(sentCount > 0){
					String mobile = String.valueOf(userService.getUserMobile(userId).get("mobile"));// 通过用户ID查询使用手机号;
					for (int i = 0; i < sentCount; i++) {
						Map<String,Object> addParam = new HashMap<String, Object>();
						addParam.put("userId", userId);
						addParam.put("mobile", mobile);
						addParam.put("voucherId",1);
						addParam.put("source","3");//兑换券来源 1：K码激活赠送 2：发现购物赠送 3：新增定期赠送 4：活动赠送 5：积分兑换 0：其他
						Map<String, String> addResult = shopVouchersService.addShopVouchers(addParam);
						if(!Consts.SUCCESS_CODE.equals(addResult.get("rescode"))){
							logger.info("定期购买，赠送电商一元购券失败！");
						}
					}
				}
			} catch (Exception e) {
				logger.error("用户"+userId+"定期购买，赠送电商一元购券失败！",e);
			}
			if(rateIdsArray!=null){
				//调用使用加息券接口
				if(rateIdsArray.length>0){
					pageMode.put("orderId", retMap.get("orderId"));
					pageMode.put("rateIds", rateIds);
					pageMode.put("productId",planId );
					
					jsonMap = this.rateRisesCouponsService.useRateRisesCoupons(pageMode);
				}
			}
			jsonMap.put("orderId", retMap.get("orderId"));
				
			String result = CommonUtil.setResultStringCn(
				jsonMap,Consts.SUCCESS_CODE, Consts.SUCCESS_DESCRIBE, "");
			
			String cpType=loanService.queryBitShowNamePeriod();
			if(remanDays==null||"".equals(remanDays.trim())||"0".equals(remanDays.trim())){
				if(!StringUtils.isBlank(investPeriod)){
					cpType+=investPeriod+"月期";
				}
				if(null!=investPeriod && "12".equalsIgnoreCase(investPeriod)){
					cpType ="超享计划";
				}
			}else{
				cpType+=remanDays+"天";
				if("365".equalsIgnoreCase(remanDays)){
					cpType ="超享计划";
				}
			}
			//ouyy 定期投资成功发送短信
			JSONObject jsonObject = JSONObject.fromObject(result);
			if(Consts.SUCCESS_CODE.equals(jsonObject.getString("rescode"))){
				//推送购买微信/短信接口
				sendMeidaAndSMS(userId,paramsMap, "108", buyCount,cpType);
				//发送个推消息----add by gongyanlan
				String smsNo="sms02001";//投资,config_sms表中参数,
				String mobile = captchaService.getMobileById(userId);//通过用户ID查询使用手机号
				String[] smsParams={buyCount,cpType,""};
				Map<String,Object> map=new HashMap<String,Object>();
				map.put("userId", userId);
				map.put("mobile", mobile);
				map.put("title", "投资通知");//标题
				map.put("messageDetailTypeNew", "4");//1.订制商品个人消息，2.还款成功，3.充值，4.投资，5,提现
				map.put("messageDetailResult", "0");//0.执行成功消息提示，1.执行失败提示
				map.put("smsParams", smsParams);//消息模板里需要替换的变量
				map.put("smsNo", smsNo);
				sMSService.sendGetuiMSG(map);
			}
			
//			//ouyy 投资成功，发送短信
//			sMSService.getSMS(userId, "sms02001", buyCount,cpType);
			
			//ouyy定期购买成功，生成借款协议
			try {
				Map<String,String> paraMap=new HashMap<String,String>();
				paraMap.put("orderId", retMap.get("orderId")==null?"":(String)retMap.get("orderId"));
				jkxyService.setJkxy("loanAgreement",paraMap);
			} catch (Exception e) {
				// TODO: handle exception
				logger.info("接口协议生成失败异常"+e.getCause());
				e.printStackTrace();
			}
			//定期购买成功，异步生成借款协议
//			ThreadPoolUtil.putRegularAgreementQueue(new RegularAgreementRunnable(centerService,retMap));
			//ouyy定期购买成功，生成借款协议成功，将文件名更新到order表中
			try {
				Map<String,String> paraMap=new HashMap<String,String>();
				String orderId=retMap.get("orderId")==null?"":(String)retMap.get("orderId");
				paraMap.put("userId", userId);
				paraMap.put("orderId", orderId);
				paraMap.put("agreementFilename", StrUtil.fileNameMD5(orderId));
				centerService.updateOrderFilename(paraMap);
			} catch (Exception e) {
				// TODO: handle exception
				logger.info("更新协议文件名到order表中发生异常"+e);
				e.printStackTrace();
			}
			
			//定期购买成功，赠送积分
			try {
				Map<String,Object> paraMap=new HashMap<String,Object>();
				String orderId=retMap.get("orderId")==null?"":(String)retMap.get("orderId");
				paraMap.put("userId", userId);
				User user = userService.getUserDetail(userId);
				paraMap.put("mobile", user.getMobile());
				paraMap.put("orderId", orderId);
				paraMap.put("dingQiAmount", buyCount);
				paraMap.put("dingQiPeriods", investPeriod); //期数
				paraMap.put("dingQiRemanDays", remanDays); //天数
				
				pointService.dingqiPoint(paraMap);
			} catch (Exception e) {
				logger.info("定期购买成功，赠送积分发生异常：",e);
				e.printStackTrace();
			}
			
			// 处理返回结果
			CommonUtil.responseJson(result, response);
			
			//=======================生成借款协议start by jiangbo=======================
//			String path = LoginRedirectUtil.agreementPath; 
//			//String path = "D:/workspackInstill/apache-tomcat-6.0.44/webapps/javaservice";
//			Configuration cfg = new Configuration();
//			//通过userID获取user信息
//			UserInfo userInfo = this.userService.getUserInfo(userId);
//
//			cfg.setDirectoryForTemplateLoading(new File(path+"/agreement/ftl/"));  //设置读取模板文件的目录
//	        Template t = cfg.getTemplate("loanAgreement.ftl");  //读取文件名为Test.ftl的模板
//	        //存储数据
//	        User user = userService.getUserDetail(userId);
//	        Map<String, Object> maps = new HashMap<String, Object>();  
//	        
//	        if(user != null) {
//	        	if(StringUtils.isNotEmpty(userInfo.getReal_name())) {
//	        		maps.put("name", userInfo.getReal_name());
//	        	}else {
//	        		maps.put("name", "");
//	        	}
//	        	if(StringUtils.isNotEmpty(user.getMobile())) {
//	        		maps.put("phone", user.getMobile());
//	        	}else {
//	        		maps.put("phone", "");
//	        	}
//	        	if(StringUtils.isNotEmpty(userInfo.getId_card())) {
//	        		maps.put("idCard", userInfo.getId_card());
//	        	}else {
//	        		maps.put("idCard", "");
//	        	}
//	        }else {
//	        	maps.put("name", "");
//	        	maps.put("phone", "");
//	        	maps.put("idCard", "");
//	        }
//	        BigDecimal decBuyAmount = new BigDecimal(buyCount);// 购买金额
//	        // 系统时间
//			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//			String sysdate = sdf.format(new Date());
//			maps.put("newDate", sysdate);
//			maps.put("buyAmount", buyCount); //购买金额
//			maps.put("buyAmount_big", NumberToCN.number2CNMontrayUnit(decBuyAmount));
//			//合同有效期
//			Scanner sc = new Scanner(System.in); 
//	        Calendar curr = Calendar.getInstance(); 
//	        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy年MM月dd日"); 
//	        curr.set(Calendar.YEAR,curr.get(Calendar.YEAR)+1); 
//	        curr.add(Calendar.DAY_OF_MONTH, -1);  
//	        Date date=curr.getTime(); 
//	        maps.put("valid_start", sdf2.format(new Date()));
//	        maps.put("valid_end", sdf2.format(date)); 
//	        //获取贷款期限和年华利率
//	        Map<String, Object> loadMap = new HashMap<String, Object>();
//	        loadMap.put("loanId", loanId);
//	        Loan loan = this.loanService.getLoanDetailByLoanId(loadMap);
//	        maps.put("interest", loan.getInterest());
//	        maps.put("loanMonths", loan.getLoanMonths()); 
//	        
//	        //获取借款合同
//	        String agreementNo = "";         //借款合同编号
//	        String agreementNoContent = "";  //借款合同内容里面编号
//	        if(loan.getLoanMonths() >= 6) {
//	        	agreementNo = this.userService.getSystemSettingValue(Consts.agreementNo.LOAN_AGREEMENT_NO_6);
//	        	agreementNoContent = this.userService.getSystemSettingValue(Consts.agreementNo.LOAN_CONTENT_AGREEMENT_NO_6);
//	        }else {
//	        	agreementNo = this.userService.getSystemSettingValue(Consts.agreementNo.LOAN_AGREEMENT_NO_OTHER);
//	        	agreementNoContent = this.userService.getSystemSettingValue(Consts.agreementNo.LOAN_CONTENT_AGREEMENT_NO_OTHER);
//	        }
//	        maps.put("agreementNo", agreementNo); 
//	        maps.put("agreementNoContent", agreementNoContent); 
//	        
//	        Writer out = new OutputStreamWriter(new FileOutputStream(
//	        		path+"/agreement/html/"+retMap.get("orderId")+".html"), "utf-8");  //输出流
//	        t.process(maps, out); //动态加载root中的数据到Test.html。数据在模板中定义好了。
	      //=======================生成借款协议end by jiangbo=======================
			
		} catch (Exception e) {
			logger.error("余额购买散标异常:" + e.getMessage());
			if(StringUtils.isNotBlank(ip)){
				IpLog.printIpLog(logBean);
			}
			String result = CommonUtil.setResultStringCn(
				new HashMap<String, Object>(),Consts.ERROR_CODE, "",Message.CnDescriptionExpression.BUSINESSE_ERROR);
			// 处理返回结果
			CommonUtil.responseJson(result, response);
		}
	}
	
	/**
	 * 根据USERID发送短信/微信
	 * @param userId
	 */
	public void sendMeidaAndSMS(String userId,Map<String,String> paramsMap,String finaceId,String buyAmount,String cpType) throws Exception{
		//封装用户ID
		WeixinMediaBinding mediaBinding = new WeixinMediaBinding();
		mediaBinding.setUserId(Integer.parseInt(userId));
		
		//先推送微信，微信成功不发短信，失败再发短信
		String mobile = captchaService.getMobileById(userId);//通过用户ID查询使用手机号
		String mediaUid = weixinBindingService.queryMediaUid(mediaBinding);//通过用户ID实体类查询微信标识
		
		//TODO 逻辑判断
		if(null == mediaUid || "null".equalsIgnoreCase(mediaUid) || "".equalsIgnoreCase(mediaUid)){
			logger.info("[推送短信息]因手机号："+mobile+"并未绑定微信");
			//发送短信
			String smsNo="sms02001";//config_sms表中参数
			String tsje=paramsMap.get("buyCount");
			if (StringUtils.isBlank(userId) 
					|| StringUtils.isBlank(smsNo)|| StringUtils.isBlank(tsje)) {
				logger.debug("deposit/join sendSMS 传入参数为空");
			}
			try{
				// 发送短信
				if(StringUtils.isEmpty(cpType)){
					 sMSService.getSMS(userId,smsNo,tsje);	
				}else{
					sMSService.getSMS(userId,smsNo,tsje,cpType);	
				}
			} catch (Exception e) {
				logger.error("deposit/join sendSMS异常:" + e.getCause());
			}
		}else{
			Map<String,String> weixinTMap = new HashMap<String,String>();
			weixinTMap.put("mediaUid", mediaUid);//微信用户唯一标识 
			if("109".equalsIgnoreCase(finaceId)){
				weixinTMap.put("productInfo", "铃铛宝活期");//产品内容
			}else{
				if("108".equalsIgnoreCase(finaceId)){
					weixinTMap.put("productInfo", cpType);//产品内容
				}else{
					weixinTMap.put("productInfo", "铃铛宝");//产品内容
				}
			}
			weixinTMap.put("number", buyAmount);//购买金额
			weixinTMap.put("functionScope", "buy");//购买金额
			
			boolean sendRusult = SendWeiXinUtil.sendWeiXin(weixinTMap);
			if(!sendRusult){
				logger.info("[微信推送失败][推送短信息]因手机号："+mobile+"并未绑定微信或者未关注联币钱包微信号");
				//发送短信
				String smsNo="sms02001";//config_sms表中参数
				String tsje=paramsMap.get("buyCount");
				if (StringUtils.isBlank(userId) 
						|| StringUtils.isBlank(smsNo)|| StringUtils.isBlank(tsje)) {
					logger.debug("deposit/join sendSMS 传入参数为空");
				}
				try{
					// 发送短信
					if(StringUtils.isEmpty(cpType)){
						 sMSService.getSMS(userId,smsNo,tsje);	
					}else{
						sMSService.getSMS(userId,smsNo,tsje,cpType);	
					}
				} catch (Exception e) {
					logger.error("deposit/join sendSMS异常:" + e.getCause());
				}
			}else{
				logger.info("[微信推送]手机号："+mobile+"推送成功");
			}
		}
	}
	
	/**
	 * 余额购买散标数据检查
	 * @param paramsMap
	 * @return
	 * @throws Exception
	 */
	private Map<String,String> buyLoanByBalanceCheck(Map<String, String> paramsMap) throws Exception{
		Map<String, String> resMap = new HashMap<String,String>();
		String userId = paramsMap.get("userId");// 用户id
		String buyCount = paramsMap.get("buyCount");// 购买份数
		String bidId = paramsMap.get("scatteredLoanId");// 购买散标id
		String setupFlag = paramsMap.get("setupFlag");// 发送标识（是来自网站用户，还是手机用户）:1：为来自网站的；2：来自手机的
		String planId = paramsMap.get("planId");// 计划id
		String loanId = paramsMap.get("loanId");
		String from = paramsMap.get("from");
		// 交易密码
		String passwordCash = paramsMap.get("passwordCash");
		//代金券Id
		String voucherId = paramsMap.get("voucherId");
		BigDecimal voucherMoney = BigDecimal.ZERO;
		
		if(null==voucherId || "".equalsIgnoreCase(voucherId) || "null".equalsIgnoreCase(voucherId)){
			// 用户id
			if (StringUtils.isBlank(userId)) {
				logger.error("余额购买散标数据检查失败： 用户id为空");
				resMap.put("code", Consts.ERROR_CODE);
				resMap.put("message", Message.CnDescriptionExpression.BUSINESSE_ERROR);
				return resMap;
			}
			
			// 理财计划ID
			if (StringUtils.isBlank(planId)) {
				logger.error("余额购买散标数据检查失败： 理财计划ID为空");
				resMap.put("code", Consts.ERROR_CODE);
				resMap.put("message", Message.CnDescriptionExpression.BUSINESSE_ERROR);
				return resMap;
			}
			//标的ID
			if (StringUtils.isBlank(loanId)) {
				logger.error("余额购买散标数据检查失败： 标的 为空");
				resMap.put("code", Consts.ERROR_CODE);
				resMap.put("message", Message.CnDescriptionExpression.BUSINESSE_ERROR);
				return resMap;
			}

			// 购买份数
			if (StringUtils.isBlank(buyCount) || Double.valueOf(buyCount) < 100) {
				logger.error("余额购买散标数据检查失败： 购买金额是:" + buyCount);
				resMap.put("code", Consts.CHECK_CODE);
				resMap.put("message", Message.CnDescriptionExpression.BUYCOUNT_IS_NULL);
				return resMap;
			}

			// 购买散标id
			if (StringUtils.isBlank(bidId)) {
				logger.error("余额购买散标数据检查失败：散标id为空");
				resMap.put("code", Consts.ERROR_CODE);
				resMap.put("message", Message.CnDescriptionExpression.BUSINESSE_ERROR);
				return resMap;
			}
			
			// 发送标识
			if(StrUtil.setupFlagCheck(setupFlag) == false){
				logger.error("余额购买散标数据检查失败： 发送标识无效！发送标识:" + setupFlag);
				resMap.put("code", Consts.ERROR_CODE);
				resMap.put("message", Message.CnDescriptionExpression.BUSINESSE_ERROR);
				return resMap;
			}
			
			//渠道
			if (StringUtils.isBlank(from)) {
				logger.error("余额购买散标数据检查失败： from的 为空");
				resMap.put("code", Consts.ERROR_CODE);
				resMap.put("message", Message.CnDescriptionExpression.BUSINESSE_ERROR);
				return resMap;
			}
			
			// 交易密码验证
			if (StringUtils.isBlank(passwordCash)) {
				logger.error("余额购买散标数据检查失败：交易密码为空");
				resMap.put("code", Consts.ERROR_CODE);
				resMap.put("message", "交易密码不能为空!");
				return resMap;
			}

			try {
				User user = userService.getUserDetail(userId);
				String passwordMd5 = MD5.md5(passwordCash);
				if (!passwordMd5.equals(user.getPassword_cash())) {
					resMap.put("code", Consts.ERROR_CODE);
					resMap.put("message", "交易密码错误，请重新输入！");
					return resMap;
				}
			} catch (Exception e) {
				resMap.put("code", Consts.ERROR_CODE);
				resMap.put("message", Message.CnDescriptionExpression.BUSINESSE_ERROR);
				return resMap;
			}
			
			/** 查询该债权是否满足购买条件 */
			Map<String,Object> paramMap = new HashMap<String,Object>();
			paramMap.put("bidId", bidId);
			Map<String,Object> bidDetailMap = centerService.checkLoanStatus(paramMap);
			if(null == bidDetailMap){
				logger.error("余额购买散标数据检查失败： 债权不满足购买条件！标的id:" + bidId);
				resMap.put("code", Consts.CHECK_CODE);
				resMap.put("message", Message.CnDescriptionExpression.BID_INVALID);
				return resMap;
			}
			
			/** 获取用户是否实名认证,对于实名认证用户取得身份证号和姓名 */
			User user = userService.getUserDetail(userId);
			// 判断用户是否实名认证
			if (!"1".equals(user.getIs_create_acct()) || !"Y".equals(user.getIdcard_validate())) {
				logger.error("余额购买散标数据检查失败：用户没有经过实名认证");
				// 没有经过实名认证不能进行购买
				resMap.put("code", Consts.CHECK_CODE);
				resMap.put("message", Message.CnDescriptionExpression.AUTHENTICATION_IS_NOT);
				return resMap;
			}
			
			/**
			 *  购买金额检查。1份起投，剩余金额不能小于购买金额
			 */
			// 查询每份金额，剩余金额
			BigDecimal perServingAmountBD = new BigDecimal(bidDetailMap.get("PER_SERVING_AMOUNT")+"");
			BigDecimal remanAmountBD = new BigDecimal(bidDetailMap.get("REMAN_AMOUNT")+"");
			logger.debug("每份金额="+perServingAmountBD+"剩余金额="+remanAmountBD);
			
			// 计算购买金额(每份金额*购买份数)
			//BigDecimal buyAmountBD = perServingAmountBD.multiply(new BigDecimal(buyCount));
			
			BigDecimal buyAmountBD = new BigDecimal(buyCount);
			logger.debug("购买金额="+buyAmountBD);
			// 购买金额不能大于剩余金额
			if(buyAmountBD.compareTo(remanAmountBD) == 1){
				logger.error("余额购买散标数据检查失败：购买金额大于剩余金额！");
				resMap.put("code", Consts.CHECK_CODE);
				resMap.put("message", Message.CnDescriptionExpression.BID_IS_INCORRECT);
				return resMap;
			}
			
			// 获取该用户的余额
			Map<String, Object> pageMode = new HashMap<String, Object>();
			pageMode.put("userId", userId);
			String acctBalanceStr = "0.00";// 余额
			Map balanceMap = centerService.getCusBalance(pageMode);
			if (balanceMap != null && "00000".equals(balanceMap.get("rescode"))) {
				acctBalanceStr = balanceMap.get("ACCTBALANCE") + "";
			} else {
				logger.error("余额购买散标查询余额失败" + balanceMap.get("resmsg"));
				resMap.put("code", Consts.ERROR_CODE);
				resMap.put("message", Message.CnDescriptionExpression.BUSINESSE_ERROR);
				return resMap;
			}

			// 余额检查
			if ("0.00".equals(acctBalanceStr) || StringUtils.isBlank(acctBalanceStr)) {
				logger.debug("余额购买散标失败,余额不足。余额为:" + String.valueOf(acctBalanceStr));
				resMap.put("code", Consts.CHECK_CODE);
				resMap.put("message", Message.CnDescriptionExpression.BALANCE_IS_INCORRECT);
				return resMap;
			}

			BigDecimal acctBalanceBD = new BigDecimal(acctBalanceStr);// 余额

			// 余额-投资金额 < 0
			if (acctBalanceBD.compareTo(buyAmountBD) < 0) {
				logger.debug("余额购买散标失败,余额不足。余额差:" + acctBalanceBD.subtract(buyAmountBD));
				resMap.put("code", Consts.CHECK_CODE);
				resMap.put("message", Message.CnDescriptionExpression.BALANCE_IS_INCORRECT);
				return resMap;
			}
			
			//判断散标是否已下架
			Integer isOffShelf = Integer.valueOf(bidDetailMap.get("IS_OFF_SHELF")+"");
			if (isOffShelf == 1){
				logger.debug("余额购买散标失败,散标已下架,下架时间：" + bidDetailMap.get("END_SALE_TIME"));
				resMap.put("code", Consts.CHECK_CODE);
				resMap.put("message", Message.CnDescriptionExpression.IS_OFF_SHELF);
				return resMap;
			}
			
			resMap.put("code", Consts.SUCCESS_CODE);
			resMap.put("message", Consts.SUCCESS_DESCRIBE);
			resMap.put("buyAmount", buyAmountBD.toString());
			return resMap;
		}else{
			Map<String,Object> reqMap = new HashMap<String,Object>();
			reqMap.put("voucherId", voucherId);
			Map<String, Object> voucherMap = new HashMap<String, Object>();
			voucherMap = this.userVouchersService.queryUserVochersById(reqMap);
			if(Consts.ERROR_CODE.equalsIgnoreCase(String.valueOf(voucherMap.get("rescode")))){
				logger.error("该代金券不存在！");
				// 该代金券不存在！
				resMap.put("code", Consts.CHECK_CODE);
				resMap.put("message", "该代金券不存在！");
				return resMap;
			}else{
				if(Consts.SUCCESS_CODE.equalsIgnoreCase(String.valueOf(voucherMap.get("rescode")))){
					UserVouchers  userVouchers = (UserVouchers)voucherMap.get("userVouchers");
					//根据代金券Id库存代金券信息
					Map<String, Object> voucherMap2 = new HashMap<String, Object>();
					voucherMap2 = this.userVouchersService.queryVochersInfoById(String.valueOf(userVouchers.getVoucher_type_id()));
					if(Consts.ERROR_CODE.equalsIgnoreCase(String.valueOf(voucherMap2.get("rescode")))){
						logger.error("该活期代金券库存不足异常");
						// 库存不足代金券异常
						resMap.put("code", Consts.CHECK_CODE);
						resMap.put("message", "该活期代金券库存不足异常");
						return resMap;
					}
					if(new BigDecimal(buyCount).compareTo(userVouchers.getInvestment_amount())<0){
						logger.error("您输入的金额未满足使用代金券规则");
						// 库存不足代金券异常
						resMap.put("code", Consts.CHECK_CODE);
						resMap.put("message", "您输入的金额未满足使用代金券规则");
						return resMap;
					}
					VouchersRule vouchersRule = (VouchersRule)voucherMap2.get("vouchersRule");
					Map<String, String> resMap2 = new HashMap<String,String>();
					voucherMoney= vouchersRule.getVoucher_amount();
				}
			}
			// 用户id
			if (StringUtils.isBlank(userId)) {
				logger.error("余额购买散标数据检查失败： 用户id为空");
				resMap.put("code", Consts.ERROR_CODE);
				resMap.put("message", Message.CnDescriptionExpression.BUSINESSE_ERROR);
				return resMap;
			}
			
			// 理财计划ID
			if (StringUtils.isBlank(planId)) {
				logger.error("余额购买散标数据检查失败： 理财计划ID为空");
				resMap.put("code", Consts.ERROR_CODE);
				resMap.put("message", Message.CnDescriptionExpression.BUSINESSE_ERROR);
				return resMap;
			}
			//标的ID
			if (StringUtils.isBlank(loanId)) {
				logger.error("余额购买散标数据检查失败： 标的 为空");
				resMap.put("code", Consts.ERROR_CODE);
				resMap.put("message", Message.CnDescriptionExpression.BUSINESSE_ERROR);
				return resMap;
			}

			// 购买份数
			if (StringUtils.isBlank(buyCount) || Double.valueOf(buyCount) < 100) {
				logger.error("余额购买散标数据检查失败： 购买金额是:" + buyCount);
				resMap.put("code", Consts.CHECK_CODE);
				resMap.put("message", Message.CnDescriptionExpression.BUYCOUNT_IS_NULL);
				return resMap;
			}

			// 购买散标id
			if (StringUtils.isBlank(bidId)) {
				logger.error("余额购买散标数据检查失败：散标id为空");
				resMap.put("code", Consts.ERROR_CODE);
				resMap.put("message", Message.CnDescriptionExpression.BUSINESSE_ERROR);
				return resMap;
			}
			
			// 发送标识
			if(StrUtil.setupFlagCheck(setupFlag) == false){
				logger.error("余额购买散标数据检查失败： 发送标识无效！发送标识:" + setupFlag);
				resMap.put("code", Consts.ERROR_CODE);
				resMap.put("message", Message.CnDescriptionExpression.BUSINESSE_ERROR);
				return resMap;
			}
			
			//渠道
			if (StringUtils.isBlank(from)) {
				logger.error("余额购买散标数据检查失败： from的 为空");
				resMap.put("code", Consts.ERROR_CODE);
				resMap.put("message", Message.CnDescriptionExpression.BUSINESSE_ERROR);
				return resMap;
			}
			
			// 交易密码验证
			if (StringUtils.isBlank(passwordCash)) {
				logger.error("余额购买散标数据检查失败：交易密码为空");
				resMap.put("code", Consts.ERROR_CODE);
				resMap.put("message", "交易密码不能为空!");
				return resMap;
			}

			try {
				User user = userService.getUserDetail(userId);
				String passwordMd5 = MD5.md5(passwordCash);
				if (!passwordMd5.equals(user.getPassword_cash())) {
					resMap.put("code", Consts.ERROR_CODE);
					resMap.put("message", "交易密码错误，请重新输入！");
					return resMap;
				}
			} catch (Exception e) {
				resMap.put("code", Consts.ERROR_CODE);
				resMap.put("message", Message.CnDescriptionExpression.BUSINESSE_ERROR);
				return resMap;
			}
			
			/** 查询该债权是否满足购买条件 */
			Map<String,Object> paramMap = new HashMap<String,Object>();
			paramMap.put("bidId", bidId);
			Map<String,Object> bidDetailMap = centerService.checkLoanStatus(paramMap);
			if(null == bidDetailMap){
				logger.error("余额购买散标数据检查失败： 债权不满足购买条件！标的id:" + bidId);
				resMap.put("code", Consts.CHECK_CODE);
				resMap.put("message", Message.CnDescriptionExpression.BID_INVALID);
				return resMap;
			}
			
			/** 获取用户是否实名认证,对于实名认证用户取得身份证号和姓名 */
			User user = userService.getUserDetail(userId);
			// 判断用户是否实名认证
			if (!"1".equals(user.getIs_create_acct()) || !"Y".equals(user.getIdcard_validate())) {
				logger.error("余额购买散标数据检查失败：用户没有经过实名认证");
				// 没有经过实名认证不能进行购买
				resMap.put("code", Consts.CHECK_CODE);
				resMap.put("message", Message.CnDescriptionExpression.AUTHENTICATION_IS_NOT);
				return resMap;
			}
			
			/**
			 *  购买金额检查。1份起投，剩余金额不能小于购买金额
			 */
			// 查询每份金额，剩余金额
			BigDecimal perServingAmountBD = new BigDecimal(bidDetailMap.get("PER_SERVING_AMOUNT")+"");
			BigDecimal remanAmountBD = new BigDecimal(bidDetailMap.get("REMAN_AMOUNT")+"");
			logger.debug("每份金额="+perServingAmountBD+"剩余金额="+remanAmountBD);
			
			// 计算购买金额(每份金额*购买份数)
			//BigDecimal buyAmountBD = perServingAmountBD.multiply(new BigDecimal(buyCount));
			
			BigDecimal buyAmountBD = new BigDecimal(buyCount);
			logger.debug("购买金额="+buyAmountBD);
			// 购买金额不能大于剩余金额
			if(buyAmountBD.compareTo(remanAmountBD) == 1){
				logger.error("余额购买散标数据检查失败：购买金额大于剩余金额！");
				resMap.put("code", Consts.CHECK_CODE);
				resMap.put("message", Message.CnDescriptionExpression.BID_IS_INCORRECT);
				return resMap;
			}
			
			// 获取该用户的余额
			Map<String, Object> pageMode = new HashMap<String, Object>();
			pageMode.put("userId", userId);
			String acctBalanceStr = "0.00";// 余额
			Map balanceMap = centerService.getCusBalance(pageMode);
			if (balanceMap != null && "00000".equals(balanceMap.get("rescode"))) {
				acctBalanceStr = balanceMap.get("ACCTBALANCE") + "";
			} else {
				logger.error("余额购买散标查询余额失败" + balanceMap.get("resmsg"));
				resMap.put("code", Consts.ERROR_CODE);
				resMap.put("message", Message.CnDescriptionExpression.BUSINESSE_ERROR);
				return resMap;
			}

			// 余额检查
			if ("0.00".equals(acctBalanceStr) || StringUtils.isBlank(acctBalanceStr)) {
				logger.debug("余额购买散标失败,余额不足。余额为:" + String.valueOf(acctBalanceStr));
				resMap.put("code", Consts.CHECK_CODE);
				resMap.put("message", Message.CnDescriptionExpression.BALANCE_IS_INCORRECT);
				return resMap;
			}

			BigDecimal acctBalanceBD = new BigDecimal(acctBalanceStr);// 余额

			// 余额-投资金额 < 0
			if ((acctBalanceBD.add(voucherMoney)).compareTo(buyAmountBD) < 0) {
				logger.debug("余额购买散标失败,余额不足。余额差:" + acctBalanceBD.subtract(buyAmountBD));
				resMap.put("code", Consts.CHECK_CODE);
				resMap.put("message", Message.CnDescriptionExpression.BALANCE_IS_INCORRECT);
				return resMap;
			}
			
			//判断散标是否已下架
			Integer isOffShelf = Integer.valueOf(bidDetailMap.get("IS_OFF_SHELF")+"");
			if (isOffShelf == 1){
				logger.debug("余额购买散标失败,散标已下架,下架时间：" + bidDetailMap.get("END_SALE_TIME"));
				resMap.put("code", Consts.CHECK_CODE);
				resMap.put("message", Message.CnDescriptionExpression.IS_OFF_SHELF);
				return resMap;
			}
			
			resMap.put("code", Consts.SUCCESS_CODE);
			resMap.put("message", Consts.SUCCESS_DESCRIBE);
			resMap.put("buyAmount", buyAmountBD.toString());
			return resMap;
			
			
		}

	}
}
	
